package cn.tedu.ivos2.audit.service.impl;

import cn.tedu.ivos2.application.mapper.ApplicationMapper;
import cn.tedu.ivos2.application.pojo.entity.Application;
import cn.tedu.ivos2.audit.mapper.AuditMapper;
import cn.tedu.ivos2.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos2.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos2.audit.pojo.entity.Audit;
import cn.tedu.ivos2.audit.pojo.vo.AuditVO;
import cn.tedu.ivos2.audit.service.AuditService;
import cn.tedu.ivos2.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos2.base.enums.AuditStatusEnum;
import cn.tedu.ivos2.user.mapper.UserMapper;
import cn.tedu.ivos2.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    public void insertAudit(Application application){
        log.debug("生成申请单对应的审批数据：application={}",application);
        List<Long> userIdList = application.getAuditUserIdList();
        for(int i=0;i<userIdList.size();i++){
            Audit audit = new Audit();
            audit.setApplicationId(application.getId());
            audit.setAuditUserId(userIdList.get(i));
            audit.setAuditSort(i);
            if(i==0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else{
                audit.setAuditStatus((AuditStatusEnum.PENDING.getCode()));
            }
            audit.setCreateTime(new Date());
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单的业务：auditQuery={}",auditQuery);
        List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
        for(int i = 0 ;i<auditVOList.size();i++){
            AuditVO auditVO = auditVOList.get(i);
            assignAuditUserList(auditVO);
        }
        return auditVOList;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批业务：auditSaveParam={}",auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        audit.setUpdateTime(new Date());
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){
            auditMapper.update(audit);
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if(count>0){
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if(auditVOList!=null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit2);
                 }
            }else{
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else if(audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())){
            auditMapper.update(audit);
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if(auditVOList!=null && auditVOList.size()>0){
                for(int i=0;i<auditVOList.size();i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if(AuditStatusEnum.PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO){
        List<String> auditUsernameList = new ArrayList<>();//创建一个用来装审批人姓名的空集合
        List<Long> auditUserIdList = new ArrayList<>();//创建一个用来装审批人id的空集合
        //根据审批单VO中的申请单id，查询当前审批单对应的申请单下的所有审批单数据
        List<AuditVO> auditVOList = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //遍历每一个审批单，获取每个审批单中的审批人id与姓名
        for(int i = 0;i<auditVOList.size();i++){
            Long userId = auditVOList.get(i).getAuditUserId();//获取当前遍历到的审批单的审批人id
            auditUserIdList.add(userId);//将当前的审批人id装到上面的id空集合中
            UserVO user = userMapper.selectById(userId);//根据用户id查出用户VO
            auditUsernameList.add(user.getUsername());//将当前的审批人姓名装到上面的name空集合中
        }
        StringJoiner stringJoiner = new StringJoiner(",");//准备拼接工具
        for(String username: auditUsernameList){//遍历审批人姓名集合并进行拼接
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);//将审批人id数据赋值给审批单VO
        auditVO.setAuditUsernameList(stringJoiner.toString());//将审批人姓名字符串赋值给审批单VO
    }

}
